package com.badlogic.androidgames;

import java.net.URL;
import java.util.HashMap;
import java.util.List;

import javax.microedition.khronos.opengles.GL10;
import org.json.JSONObject;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import com.badlogic.androidgames.asyncutil.AsyncJSONBroker;
import com.badlogic.androidgames.asyncutil.JSONReq;
import com.badlogic.androidgames.framework.Game;
import com.badlogic.androidgames.framework.Input.TouchEvent;
import com.badlogic.androidgames.framework.gl.Camera2D;
import com.badlogic.androidgames.framework.gl.SpriteBatcher;
import com.badlogic.androidgames.framework.gl.Texture;
import com.badlogic.androidgames.framework.gl.TextureRegion;
import com.badlogic.androidgames.framework.impl.GLScreen;
import com.badlogic.androidgames.framework.impl.GLGame.GLGameState;
import com.badlogic.androidgames.framework.math.OverlapTester;
import com.badlogic.androidgames.framework.math.Rectangle;
import com.badlogic.androidgames.framework.math.Vector2;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.Util;

public class MainMenuScreen extends GLScreen {
	Camera2D guiCam;
	SpriteBatcher batcher;
	Rectangle playBounds;
	Rectangle playFreeBounds;
	Rectangle loginBounds;
	Rectangle difficultBounds;
	boolean logged=false;
	Vector2 touchPoint;
	final Facebook facebook;
	final SharedPreferences sharedPreferences;

	static String name;

	public MainMenuScreen(Game game) {
		super(game);

		facebook = new Facebook("307086602703463");

		sharedPreferences = glGame.getApplicationContext()
				.getSharedPreferences("facebook-credentials",
						Context.MODE_PRIVATE);
		String tok = sharedPreferences.getString("access_token", null);
		facebook.setAccessToken(tok);
		facebook.setAccessExpires(sharedPreferences.getLong("expires_in", 0));

		/*
            mPrefs = glGame.getPreferences(glGame.MODE_PRIVATE);
            String access_token = mPrefs.getString("access_token", null);
            long expires = mPrefs.getLong("access_expires", 0);
            if(access_token != null) {
                facebook.setAccessToken(access_token);
            }
            if(expires != 0) {
                facebook.setAccessExpires(expires);
            }
		 */  
		
		if (!facebook.isSessionValid()) 
		{
			facebookAuth();
		}		
		
		//batcher.drawSprite(240, 400, 600, 220, Assets.mainMenu);//
		
		
		guiCam = new Camera2D(glGraphics, 480, 800);
		batcher = new SpriteBatcher(glGraphics, 100);
		playBounds = new Rectangle(240-184, 260, 184*2, 34*2);
		playFreeBounds = new Rectangle(240-300, 420, 300*2, 34*2);
		loginBounds= new Rectangle(240-92, 80, 184, 34);
		difficultBounds= new Rectangle(240-125, 180, 250, 34);
		
		touchPoint = new Vector2();

		Settings.load(game.getFileIO());
	}

	
	 void facebookAuth()
	 {
		 glGame.runOnUiThread(new Runnable() 
		 {
			 public void run() 
			 {
				 facebook.authorize(glGame, 
						 new String[] { "email", "publish_checkins", 
						 "publish_actions", "read_stream"},
						 Facebook.FORCE_DIALOG_AUTH, new DialogListener() {
					 @Override
					 public void onComplete(Bundle values) 
					 {
						 SharedPreferences.Editor editor = sharedPreferences.edit();
						 String tt = facebook.getAccessToken();
						 editor.putString("access_token", tt);
						 editor.putLong("access_expires", facebook.getAccessExpires());
						 editor.commit();
					 }

					 @Override
					 public void onFacebookError(FacebookError error) 
					 {
					 }

					 @Override
					 public void onError(DialogError e) 
					 {
					 }

					 @Override
					 public void onCancel() 
					 {
					 }
				 });
			 }
		 });
	 }
	 
	 
	@Override
	public void update(float deltaTime) {
		
		if(glGame.backPressed == true)
		{
			glGame.backPressed = false;
			glGame.finish();
		}
		
		List<TouchEvent> touchEvents = game.getInput().getTouchEvents();
		game.getInput().getKeyEvents();

		int len = touchEvents.size();
		for (int i = 0; i < len; i++) {
			TouchEvent event = touchEvents.get(i);
			touchPoint.set(event.x, event.y);
			guiCam.touchToWorld(touchPoint);

			if (event.type == TouchEvent.TOUCH_UP) {
				if (OverlapTester.pointInRectangle(playBounds, touchPoint)&&logged == true) 
				{
					glGame.gameUserData.freeMode = false;
					game.setScreen(new GameScreen(game));
					return;
				}
				if (OverlapTester.pointInRectangle(playFreeBounds, touchPoint)&&logged == true) 
				{
					glGame.gameUserData.freeMode = true;
					game.setScreen(new GameScreen(game));
					return;
				}
				if (OverlapTester.pointInRectangle(difficultBounds, touchPoint)&&logged == true) 
				{
                    glGame.runOnUiThread(new Runnable() {
	                    public void run() {
	                    	glGame.myDialog.setContentView(R.layout.difficult);
	                    	Spinner spinner = (Spinner) glGame.myDialog.findViewById(R.id.spinnerDifficult);
	                    	ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(glGame,
	                    	        R.array.difficult_array, android.R.layout.simple_spinner_item);
	                    	adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	                    	spinner.setAdapter(adapter);
	                    	spinner.setSelection(Settings.gameDifficult.ordinal());
	                    	spinner.setOnItemSelectedListener(glGame.myDialogHandler);
	                    	
	                    	Button button = (Button)glGame.myDialog.findViewById(R.id.buttonDifficultOk);
	                        button.setOnClickListener(glGame.myDialogHandler);
	                    	
	                        glGame.myDialog.show();
	                        glGame.state = GLGameState.Paused;                  
	                    }});
					
					return;
				}
				if (OverlapTester.pointInRectangle(loginBounds, touchPoint)) 
				{
					if(logged == false)
					{
						facebookAuth();
					}
					else
					{
						try {
							Log.d("logout", "logout");
							facebook.logout(glGame);

							Assets.facebookImage = null;

							SharedPreferences.Editor editor = sharedPreferences
									.edit();
							String tt = facebook.getAccessToken();
							editor.putString("access_token", tt);
							editor.putLong("access_expires",
									facebook.getAccessExpires());
							editor.commit();

							logged = false;
							
							glGame.gameUserData.facebook = null;

							Log.d("logout", "logout");
						} 
						catch (Exception e) 
						{
							e.printStackTrace();
						}
						return;
					}
					return;
				}
			}
		}

		if (facebook.isSessionValid() && Assets.facebookImage == null) 
		{
			try 
			{
				String jsonUser = facebook.request("me");
				JSONObject obj = Util.parseJson(jsonUser);
				String facebookId = obj.optString("id");
				name = obj.optString("name");
				String userName = obj.optString("username");

				URL img_value = null;
				img_value = new URL("http://graph.facebook.com/" + facebookId
						+ "/picture?type=large");
				
				Assets.facebookTexture = new Texture(glGame, img_value);
				Assets.facebookImage = new TextureRegion(
						Assets.facebookTexture, 0, 0,
						Assets.facebookTexture.width,
						Assets.facebookTexture.height);
				
				logged = true;
				
				glGame.gameUserData.facebook = facebook;
				
				
				//gestione del login con le api di greatminds
				String path = "http://lenny.cs.indiana.edu:7489/greatminds/users/login";
				HashMap<String, String> params = new HashMap<String, String>();

				params.put(new String("user_id"), userName);
				params.put(new String("full_name"), name);

				JSONReq req = new JSONReq();
				req.path = path;
				req.params = params;

				AsyncJSONBroker resp = (AsyncJSONBroker) new AsyncJSONBroker(glGame).execute(req);

				JSONObject res = resp.get();
							
				glGame.gameUserData.username = userName;
				glGame.gameUserData.name = name;
				glGame.gameUserData.points = res.getJSONObject("user").getInt("score");
			}
			catch (Exception e) 
			{
				e.printStackTrace();
			}
		}
	}

	@Override
	public void present(float deltaTime) 
	{
		GL10 gl = glGraphics.getGL();
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
		guiCam.setViewportAndMatrices();

		gl.glEnable(GL10.GL_TEXTURE_2D);

		batcher.beginBatch(Assets.backgroundMenu);
			batcher.drawSprite(240, 400, 480, 800, Assets.backgroundMenuRegion);
		batcher.endBatch();

		gl.glEnable(GL10.GL_BLEND);
		gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);

		//batcher.beginBatch(Assets.items);
			//batcher.drawSprite(240, 400, 600, 220, Assets.mainMenu);
		//batcher.endBatch();

		if (Assets.facebookImage == null) 
		{
			// batcher.beginBatch(Assets.items);
			// batcher.drawSprite(160, 200-200, 300, 110,
			// Assets.facebookImage1);
			// batcher.endBatch();
		} 
		else 
		{

			batcher.beginBatch(Assets.facebookTexture);
				batcher.drawSprite(240, 700, Assets.facebookTexture.width / 2,
					Assets.facebookTexture.height / 2, Assets.facebookImage);
			batcher.endBatch();
			batcher.beginBatch(Assets.fontTexture);
				Assets.font.drawText(batcher, name, 2000 / name.length(), 630);
			batcher.endBatch();
		}

		if (logged == false) 
		{
			batcher.beginBatch(Assets.login);
				batcher.drawSprite(240, 100, 184,34, Assets.loginRegion);
			batcher.endBatch();
		}
		else 
		{
			batcher.beginBatch(Assets.playGame);
				batcher.drawSprite(240, 300, 184*2,34*2, Assets.playGameRegion);
			batcher.endBatch();
			
			batcher.beginBatch(Assets.playGameFree);
				batcher.drawSprite(240, 450, 300*2,34*2, Assets.playGameFreeRegion);
			batcher.endBatch();
			
			batcher.beginBatch(Assets.difficultGame);
				batcher.drawSprite(240, 200, 250,34, Assets.difficultGameRegion);
			batcher.endBatch();
			
			batcher.beginBatch(Assets.logout);
				batcher.drawSprite(240, 100, 184,34, Assets.logoutRegion);
			batcher.endBatch();
		}
		gl.glDisable(GL10.GL_BLEND);
	}

	@Override
	public void pause() 
	{
		Settings.save(game.getFileIO());
	}

	@Override
	public void resume() 
	{
		Assets.facebookImage = null;
	}

	@Override
	public void dispose() 
	{
	}
}
